package Thread;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * @className: Timer
 * @author: 芃
 * @description: 定时器
 * @date: 2024/1/14 20:48
 */
class MyTask implements Comparable<MyTask>{
    private Runnable runnable;//任务具体要干啥
    private long time;//任务具体啥时候干,保存任务要执行的毫秒级时间戳

    public MyTask(Runnable runnable, long delay) {//after是一个时间间隔,不是绝对的时间戳的值
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public void run(){
        runnable.run();
    }
    public long getTime(){
        return time;
    }
    @Override
    public int compareTo(MyTask o){
        //到底谁减谁,才是一个时间小的在前
        return (int) (this.time - o.time);
    }
}
class MyTimer{
    //定时器内部能够存放多个任务
    private PriorityBlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
    private final Object locker = new Object();//锁对象

    public void schedule(Runnable runnable,long delay){
        MyTask task = new MyTask(runnable,delay);
        queue.offer(task);
        //每次任务插入成功之后,都唤醒一下扫描线程,让线程重新检查一下队首的任务看是否时间到要执行
        synchronized (locker){
            locker.notify();
        }
    }

    public MyTimer(){
        Thread t = new Thread(() ->{
            while (true){
                try {
                    synchronized (locker){
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        //先取出队首元素
                        MyTask task = queue.peek();
                        //再比较一下看看当前这个任务时间到了没有???
                        long curTime = System.currentTimeMillis();
                        if(curTime < task.getTime()){
                            //避免盲等
                            locker.wait(task.getTime() - curTime);
                        }else {
                            //时间到了,执行任务
                            task.run();
                            queue.poll();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
public class Timer {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        for (int i = 0; i < 5; i++) {
            int val = i;
            timer.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello world->" + val );
                }
            }, 1000 * i );
        }
    }
}
